import set from 'lodash/set';
import permissionCheckResolveDecorate from '@kuiper/auth/dist/server/lib/permissionCheckResolveDecorate';
import errorCodesBuilder from '../../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('');

async function resolver(root, args, context) {
	const {
		request: {
			log,
			headers: { cookie },
			server: {
				app: {
					model: { Asset },
				},
				methods: { createOrUpdateTask },
			},
		},
	} = context;

	let prevRecord;
	try {
		prevRecord = await Asset.findOne(args.filter).populate('jobId').lean();
		if (!prevRecord) {
			throw new Error(`updateOne Asset not found ${args.filter._id}`);
		}
	} catch (err) {
		const error = errorCodes['[03]更新资产信息: 查找资产失败'].from(err);
		log.error({ error, assetId: args.filter._id }, error.rawMessage);
		throw error;
	}

	if (!prevRecord?.jobId?.verification?.isVerified) {
		const error = errorCodes['[02]不允许更新未通过验证的资产'];
		log.error({ error, target: prevRecord.target.host }, error.rawMessage);
		throw error;
	}

	if (!args.record.taskSettings) {
		args.record.taskSettings = prevRecord.taskSettings;
	}

	const record = { ...prevRecord, ...args.record };

	let { enableMonitor, immediateExec } = args;
	enableMonitor =
		enableMonitor === undefined
			? prevRecord?.jobId?.enableMonitor
			: enableMonitor;
	try {
		await createOrUpdateTask({
			cookie,
			enableMonitor,
			taskType: 'asset',
			triggerType: 'schedule',
			body: {
				immediateExec,
				enableMonitor,
				jobId: prevRecord?.jobId?._id,
				sourceIp: prevRecord?.jobId?.sourceIp,
				taskSettings: record.taskSettings || prevRecord.taskSettings,
			},
		});
	} catch (err) {
		args.record.taskSettings.enable = false;
		const error = errorCodes['[03]更新资产信息: 创建资产变动任务失败'].from(
			err
		);
		log.error({ error, target: prevRecord.target }, error.rawMessage);
		throw error;
	}

	console.log('[  ]-73', record);
	log.audit(
		{
			affects: [record.jobId.targetUrl],
			jobId: prevRecord.id,
			module: 'job',
			actionType: 'update',
			actionMessage: '更新资产变动配置',
			detail: `更新${record.jobId.note}资产变动配置，资产地址：${
				record.jobId.targetUrl
			}，${enableMonitor ? '开启' : '关闭'}周期监测开关，${
				record.taskSettings.enable ? '开启' : '关闭'
			}资产变动监测，${record.jobId.enableAlert ? '开启' : '关闭'}告警开关`,
		},
		`[${prevRecord.target}]启用监测任务`
	);
	return { record, recordId: record._id };
}

export const resolve = permissionCheckResolveDecorate({
	required: 'cloud-monitor\x01editAsset',
	selfOnlyArgsBuilder(
		_source,
		args,
		{
			request: {
				auth: {
					credentials: { uid },
				},
			},
		}
	) {
		set(args, ['filter', 'uid'], uid);
	},
})(resolver);

export default {
	resolve,
	description: '更新资产',
	type: 'UpdateOneAssetPayload',
	args: {
		immediateExec: 'Boolean',
		enableMonitor: 'Boolean',
		filter: 'FilterUpdateOneAssetInput!',
		record: 'UpdateOneAssetInput!',
	},
};
